library(lme4)
library(doBy)
library(texreg)
library(xtable)
library(rdd)
library(reshape2)
library(gridExtra)
library(ggplot2)
library(dplyr)
library(pBrackets)
library(stargazer)

the_prefix <- ""

setwd("")

load(
    "data/kff_main_replication_data_with_psraid.RData"
)

### recode variables
sdat$AGEN <- as.numeric(as.character(sdat$AGE))

sdat$labels <- NA
sdat$labels[sdat$PID==1] <- "Dem"
sdat$labels[sdat$PID==2] <- "Ind"
sdat$labels[sdat$PID==3] <- "GOP"

sdat$PERIOD <- cut(sdat$DATN, c(0, seq(13, 109, 6)), right=FALSE)
levels(sdat$PERIOD) <- 0:16
summary(sdat$PERIOD)
sdat$PERIOD <- as.numeric(sdat$PERIOD)-1

## load("kff_survey_weights_Feb2009_to_Aug2017.RData")

## kff_weights$NUMBER <- kff_weights$survey

## sdat <- merge(
##     sdat,
##     kff_weights %>% dplyr::select(-DATE),
##     by=c("PSRAID","NUMBER"),
##     all.x=T
## )

sdat.under65 <- subset(
    sdat, AGEN < 65 & !(DATN %in% c(NA)) & !(AGEN %in% c(NA))
)

sdat.under65.pre <- subset(
    sdat.under65,
    DATN < 61
)
sdat.under65.post <- subset(
    sdat.under65,
    DATN > 60 & !(DATN %in% c(96,105))
)

sdat.under65.2 <- subset(
    sdat.under65,
    !(DATN %in% c(96,105))
)

## PID: from 1 - Dem, 2 - Ind, 3 - GOP
##      to 1 - Dem, 0.5 - Ind, 0 - GOP
sdat.under65.2$DEM <- with(
    sdat.under65.2,
    abs(((PID-1)/2)-1)
)
